<template>
  <view class="choose-image">
    <view class="bg-img" v-if="Value" @click="ViewImage">
      <image :src="baseUrl+Value" mode="aspectFill" class="image"></image>
      <text class='cuIcon-close close' @tap.stop="DelImg"></text>
    </view>
    <view class="solids" @tap="ChooseImage" v-else>
      <text class='cuIcon-pic icon'></text>
    </view>
  </view>
</template>

<script>
import Api from "@/utils/Api";
import {baseUrl} from "@/utils/request";

export default {
  name: "form-image",
  data() {
    return {
      baseUrl,
      Value: this.value,
    }
  },
  props: {
    value: String,
  },
  watch: {
    Value(val) {
      this.$emit('update:value', val);
    },
    value(val){
      this.Value = val;
    },
  },
  methods: {
    getImageModel(img) {
      let host = img.split("/").slice(0, 3).join("/");
      let src = "/" + img.split("/").slice(3).join("/")
      return {src, host}
    },
    ViewImage() {
      let image = baseUrl + this.Value
      uni.previewImage({
        urls: [image],
        current: image
      });
    },
    DelImg() {
      this.Value = null;
    },
    ChooseImage() {
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: (res) => {
          this.uploadImage(res.tempFilePaths[0]);
        }
      });
    },
    uploadImage(file) {
      Api.uploadImage(file).then(res => {
        let {src, host} = res[0];
        this.Value = src;
      })
    },
  },
}
</script>

<style lang='scss'>
.choose-image {
  margin: r(30px 0);
}

.bg-img {
  width: r(200px);
  height: r(200px);
  position: relative;

  .image {
    width: 100%;
    height: 100%;
  }

  .close {
    position: absolute;
    right: 0;
    top: 0;
    color: white;
    background-color: rgba(#000000, .3);
    padding: r(10px);
  }

}

.solids {
  width: r(200px);
  height: r(200px);
  display: flex;
  align-items: center;
  justify-content: center;

  .icon {
    font-size: r(40px);
  }
}
</style>